package com.itheima.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.exception.MyException;
import com.itheima.common.utils.BaseContext;
import com.itheima.entity.*;
import com.itheima.entity.dto.OrdersDto;
import com.itheima.mapper.OrdersMapper;
import com.itheima.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhengbinghua
 * @since 2023-03-02
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private OrdersDetailsService ordersDetailsService;
    @Autowired
    private  ShoppingCartService shoppingCartService;

/**提交订单
 * */
    @Override
    @Transactional
    public void submit(Orders orders) {
        //1.获取用户id
        String userId = BaseContext.getCurrentId();
        //购物车数据
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId,userId);
        //获得用户名下的所有购物车列表
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(wrapper);
        if (null==shoppingCarts||shoppingCarts.size()==0){
            throw new MyException(404, "购物车不存在,不能下单！");
        }
        //查询用户数据
        User user= userService.getById(userId);
        //查询地址数据
        String addressBookId = orders.getAddressBookId();
        //获取地址信息
        AddressBook addressBook = addressBookService.getById(addressBookId);
        //判断地址是否存在
        if (addressBook==null){
            throw new MyException(404, "默认地址不存在，不能下单");
        }
        //订单表添加数据
        //生成订单id(long类型)
        long id = IdWorker.getId();
        //初始金额设定0
        AtomicInteger amount = new AtomicInteger(0);
        //2.便历购物车，设置订单明细信息
     List<OrdersDetails> detailsList= shoppingCarts.stream().map(item->{
          //这里的item是shoppingcart对象
          OrdersDetails ordersDetails = new OrdersDetails();
          //long-->string
          ordersDetails.setOrdersId(String.valueOf(id));
          ordersDetails.setNumber(item.getNumber());
          ordersDetails.setFlavor(item.getDishFlavor());
          ordersDetails.setDishId(item.getDishId());
          ordersDetails.setSetmealId(item.getSetmealId());
          ordersDetails.setName(item.getName());
          ordersDetails.setAmount(item.getAmount());
          ordersDetails.setImage(item.getImage());
          //计算金额
          amount.addAndGet(item.getAmount()
                  .multiply(new BigDecimal(item.getNumber()))
                  .intValue());
          return ordersDetails;
              }).collect(Collectors.toList());

      //设置订单信息
        orders.setNumber(String.valueOf(id));
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus("2");
        //设置金额
        orders.setAmount(new BigDecimal(amount.get()));
        //设置收件人信息
        orders.setConsignee(addressBook.getConsignee());
        //设置电话
        orders.setPhone(addressBook.getPhone());
        //设置地址
        orders.setAddress(addressBook.getDetail());
        //3.保存订单信息
        ordersService.save(orders);
        //4.订单明细表添加数据
        ordersDetailsService.saveBatch(detailsList);

        //5.结算完成，清空当前用户的购物车信息
        shoppingCartService.remove(wrapper);

    }

    /**订单分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public Page<OrdersDto> userpage(Integer page, Integer pageSize) {
        //分页信息
        Page<Orders> orderspage = new Page<>(page, pageSize);
        //条件
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Orders::getOrderTime);
        //执行分页查询
        this.page(orderspage, wrapper);

        //封装一个dto对象
        Page<OrdersDto> ordersDtoPage = new Page<>();
        //复制属性，去掉分页信息
        BeanUtil.copyProperties(orderspage, ordersDtoPage, "records");

        //获得orders表的分页数据
        List<Orders> ordersList = orderspage.getRecords();
        //便历集合
       List<OrdersDto> ordersDtoList =ordersList.stream().map(orders->{
                       //构造条件
            LambdaQueryWrapper<OrdersDetails> wrapper1 = new LambdaQueryWrapper<>();
            //订单明细表添加订单id
            wrapper1.eq(OrdersDetails::getOrdersId,orders.getId());
           //查询所有订单明细
           List<OrdersDetails> list = ordersDetailsService.list(wrapper1);
           //复制属性
           OrdersDto ordersDto = new OrdersDto();
           BeanUtil.copyProperties(orders, ordersDto);
           ordersDto.setOrdersDetails(list);
           //返回对象
           return ordersDto;
       }).collect(Collectors.toList());
       //设置分页记录
       ordersDtoPage.setRecords(ordersDtoList);
        return ordersDtoPage;
    }
}
